import departmentApi from '@/pages/Organization/DepartmentManagement/request';
import groupBaseApi from '@/pages/Organization/GroupBaseManagement/request';
import roleApi from '@/pages/Organization/RoleManagement/role-request';
import subsidiaryBaseApi from '@/pages/Organization/SubsidiaryBaseManagement/request';
import userApi from '@/pages/Organization/UserManagement/request';
import { PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form } from 'antd';
import { useMemo, useState } from 'react';
import { useModel } from 'umi';

export type Data = UserManagementApi.InfoResponse;
export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  data?: UserManagementApi.ListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}
const colSpan = 2;
function UserManagementForm(props: Props) {
  const { data } = props;
  const isEdit = useMemo(() => !!data?.id, [data?.id]);
  const [form] = Form.useForm<Data>();
  const { initialState } = useModel('@@initialState');

  const [subsidiaryBaseList, setSubsidiaryBaseList] = useState<
    SubsidiaryBaseManagementApi.InfoResponse[]
  >([]);
  const [departmentList, setDepartmentList] = useState<DepartmentManagementApi.InfoResponse[]>([]);
  const [roleList, setRoleList] = useState<RoleManagementApi.InfoResponse[]>([]);
  const [userList, setUserList] = useState<UserManagementApi.ListResponse[]>([]);

  const [info, setInfo] = useState<Partial<UserManagementApi.InfoResponse>>({});

  const subsidiaryBaseListOptions = useMemo(
    () => subsidiaryBaseList.map((item) => ({ label: item.subsidiaryName, value: item.id })),
    [subsidiaryBaseList],
  );
  const departmentOptions = useMemo(
    () => departmentList.map((item) => ({ label: item.departmentName, value: item.id })),
    [departmentList],
  );
  const roleOptions = useMemo(
    () => roleList.map((item) => ({ label: item.roleName, value: item.id })),
    [roleList],
  );
  const userOptions = useMemo(
    () => userList.map((item) => ({ label: item.realname, value: item.id })),
    [userList],
  );

  const getAllSubsidiaryBaseList = async () => {
    const list = await subsidiaryBaseApi.getSelectList(initialState?.userInfo?.id);
    setSubsidiaryBaseList(list);
  };
  const getAllDepartmentList = async (parmas: DepartmentManagementApi.SelectParams) => {
    const list = await departmentApi.getSelectList(parmas, initialState?.userInfo?.id);
    setDepartmentList(list);
  };
  const getAllRoleList = async (params: RoleManagementApi.SelectParams) => {
    const list = await roleApi.getSelectList(params, initialState?.userInfo?.id);
    setRoleList(list);
  };
  const getAllUserList = async () => {
    const list = await userApi.getAllList({ roleId: initialState?.userInfo?.userRoleId });
    setUserList(list);
  };
  const getInfo = async (params: UserManagementApi.InfoParams) => {
    const userInfo = await userApi.getInfo(params);
    const { roleDepartmentLists } = userInfo;
    if (roleDepartmentLists && roleDepartmentLists.length) {
      const roleDepartment = roleDepartmentLists[0];
      const { groupID, subsidiaryID, departmentId, userRoleId } = roleDepartment;
      Object.assign(userInfo, { groupID, subsidiaryID, departmentId, userRoleId });
    }
    if (userInfo.subsidiaryID) {
      getAllDepartmentList({ SubsidiaryID: userInfo.subsidiaryID });
    }
    if (userInfo.departmentId) {
      getAllRoleList({ DepartmentId: userInfo.departmentId });
    }
    form.setFieldsValue(userInfo);
    setInfo(userInfo);
  };
  const findData = (
    value: string,
    options: {
      label: string;
      value: string;
    }[],
  ) => {
    for (let item of options) {
      if (item.value === value) return item;
    }
    return { label: '', value: '' };
  };
  const onSubmit = async (form: any) => {
    const groupBaseList = await groupBaseApi.getAllList();
    const groupID = groupBaseList[0]?.id || '';

    const { realname, mobileno, parentID, subsidiaryID, departmentId, userRoleId } = form;
    const { id = '' } = info;
    const parentUser = findData(parentID, userOptions);
    if (isEdit) {
      const params: UserManagementApi.UpdateParams = {
        id,
        realname,
        mobileno,
        parentId: parentID,
        parentName: parentUser.label,
        groupID: groupID,
        subsidiaryID: info.subsidiaryID,
        departmentList: [{ departmentId, userRoleId }],
      };
      const data = await userApi.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: UserManagementApi.CreateParams = {
        realname,
        mobileno,
        parentId: parentID,
        parentName: parentUser.label,
        nickname: mobileno,
        groupID,
        subsidiaryID,
        departmentList: [{ departmentId, userRoleId }],
      };
      const data = await userApi.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };
  const onOpenChange = (open: boolean) => {
    if (open) {
      if (!!data && !!data.id) {
        getInfo({ id: data.id });
      }
      getAllSubsidiaryBaseList();
      getAllUserList();
    } else {
      form.resetFields();
      props.onCancel?.();
    }
  };

  const formConfig = useMemo(() => {
    const subsidiaryID = {
      Component: ProFormSelect,
      props: {
        name: 'subsidiaryID',
        rules: [{ required: true }],
        width: 'md',
        label: '所属子公司',
        placeholder: '请选择所属子公司',
        options: subsidiaryBaseListOptions,
        onChange: (SubsidiaryID: string) => {
          getAllDepartmentList({ SubsidiaryID });
        },
      },
    };
    const departmentId = {
      Component: ProFormSelect,
      props: {
        name: 'departmentId',
        rules: [{ required: true }],
        width: 'md',
        label: '所属部门',
        variant: 'borderless',
        placeholder: '请选择所属部门',
        options: departmentOptions,
        onChange: (DepartmentId: string) => {
          getAllRoleList({ DepartmentId });
        },
      },
    };
    const userRoleId = {
      Component: ProFormSelect,
      props: {
        name: 'userRoleId',
        rules: [{ required: true }],
        width: 'md',
        label: '用户角色',
        placeholder: '请选择用户角色',
        options: roleOptions,
      },
    };
    const realname = {
      Component: ProFormText,
      props: {
        name: 'realname',
        rules: [{ required: true }],
        width: 'md',
        label: '姓名',
        placeholder: '请输入姓名',
      },
    };
    const mobileno = {
      Component: ProFormText,
      props: {
        name: 'mobileno',
        width: 'md',
        label: '手机号',
        placeholder: '请输入手机号',
        rules: [{ required: true }, { pattern: /^1\d{10}/, message: '请输入正确的手机号' }],
      },
    };
    const parentID = {
      Component: ProFormSelect,
      props: {
        name: 'parentID',
        width: 'md',
        label: '用户上级',
        placeholder: '请选择用户上级',
        options: userOptions,
      },
    };

    const createForm: {
      [key in string]: FormConfig;
    } = { subsidiaryID, departmentId, userRoleId, realname, mobileno, parentID };
    const updateForm: {
      [key in string]: FormConfig;
    } = {
      subsidiaryID,
      departmentId,
      userRoleId,
      realname,
      mobileno,
      parentID,
    };
    return isEdit ? updateForm : createForm;
  }, [isEdit, subsidiaryBaseListOptions, departmentOptions, roleOptions, userOptions]);
  const drawerFormData = useMemo(() => {
    const data: FormConfig[][] = [];
    const keys = Object.keys(formConfig);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const index = Math.floor(i / colSpan);
      if (!data[index]) data[index] = [];
      data[index].push(formConfig[key]);
    }
    return data;
  }, [formConfig]);

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}用户`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      {drawerFormData.map((item, i) => {
        return (
          <ProForm.Group key={i}>
            {item.map((data) => {
              const { props, Component } = data;
              return <Component key={props.name} {...props} />;
            })}
          </ProForm.Group>
        );
      })}
    </DrawerForm>
  );
}

export default UserManagementForm;
